<template>
  <current>
    <div v-loading="loading" class="common-container center-container">
      <div class="common-header"><h3 class="common-header-title">项目设置</h3></div>
      <div class="general-content">
        <el-collapse v-model="activeNames">
          <el-collapse-item class="general-settings" :name="ActiveEnum.info">
            <template #title>
              <div class="settings-header">
                <h4>项目信息</h4>
                <el-button class="collapse-btn">{{ toggleText(ActiveEnum.info) }}</el-button>
              </div>
            </template>
            <el-form
              ref="infoFormRef"
              size="large"
              :model="infoForm"
              :rules="infoRules"
              label-position="top"
            >
              <el-row>
                <el-col class="flex flex-justify-between">
                  <el-form-item label="项目名称" prop="name" class="mr-[20px] flex-1">
                    <el-input v-model="infoForm.name" :placeholder="$t('form.placeholder')" />
                  </el-form-item>
                  <el-form-item class="w-180" label="项目编号" prop="license">
                    <el-input v-model="infoForm.license" :placeholder="$t('form.placeholder')" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="简要标题" prop="nameShort">
                    <el-input v-model="infoForm.nameShort" :placeholder="$t('form.placeholder')" />
                  </el-form-item>
                  <el-form-item label="方案号" prop="purposeValue">
                    <el-input
                      v-model="infoForm.purposeValue"
                      :placeholder="$t('form.placeholder')"
                    />
                  </el-form-item>
                  <el-form-item label="项目周期" prop="cycle">
                    <el-date-picker
                      v-model="infoForm.cycle"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>

                  <el-form-item label="关键字" prop="keyValue">
                    <el-input v-model="infoForm.keyValue" :placeholder="$t('form.placeholder')" />
                  </el-form-item>
                </el-col>
                <el-col :span="2" />
                <el-col :span="10" class="flex flex-items-center">
                  <hold-upload
                    class="icon-uploader"
                    list-type="picture"
                    :file-list="[]"
                    :limit="1"
                    file-name="headPhoto"
                    file-type=".png,.jpg,.jpeg"
                    :show-file-list="false"
                    :avatar-url="infoForm.icon ? formatUrl(infoForm.icon) : ''"
                    @success="uploadSuccess"
                  />
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="适应症" prop="indications">
                    <el-input
                      v-model="infoForm.indications"
                      :placeholder="$t('form.placeholder')"
                      :autosize="{ minRows: 2 }"
                      type="textarea"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="项目描述" prop="depict">
                    <el-input
                      v-model="infoForm.depict"
                      :placeholder="$t('form.placeholder')"
                      :autosize="{ minRows: 2 }"
                      type="textarea"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="申办方" prop="sponsor">
                    <select-form
                      v-model="infoForm.sponsor"
                      :options="orgList"
                      :multiple="false"
                      :default-props="{ label: 'name', value: 'oid' }"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="项目阶段" prop="phase">
                    <select-form
                      v-model="infoForm.phase"
                      :options="dictData[dictIdMaps.projectPhase]"
                      :multiple="false"
                      :default-props="{ label: 'value', value: 'code' }"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="项目类型" prop="sort">
                    <select-form
                      v-model="infoForm.sort"
                      :options="dictData[dictIdMaps.projectType]"
                      :multiple="false"
                      :default-props="{ label: 'value', value: 'code' }"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div>
              <el-button type="primary" :loading="saveInfoLoading" @click="saveInfo">{{
                saveInfoLoading ? '' : '保存'
              }}</el-button>
            </div>
          </el-collapse-item>
          <!-- <el-collapse-item class="general-settings" name="2">
            <template #title>
              <div class="settings-header">
                <h4>项目约束</h4>
                <el-button class="collapse-btn">{{ toggleText('2') }}</el-button>
              </div>
            </template>

            <el-form
              ref="constraintFormRef"
              :model="constraintForm"
              :rules="constraintRules"
              label-position="top"
            >
              <el-row>
                <el-col :span="11">
                  <el-form-item label="预期受试者数量" prop="expectNum" class="w100">
                    <el-input-number v-model="constraintForm.expectNum" :step="1" :min="1" />
                    <el-checkbox v-model="constraintForm.expectDisable" style="margin-left: 20px"
                      >达到数量时禁止添加新受试者</el-checkbox
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="2" />
                <el-col :span="11">
                  <el-form-item label="性别限制" prop="restrictSex">
                    <select-form
                      v-model="constraintForm.restrictSex"
                      :options="dictData[dictIdMaps.sex]"
                      :multiple="false"
                      :default-props="{ label: 'value', value: 'code' }"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="2">
                  <el-form-item label="年龄限制" prop="ageDisable">
                    <el-switch
                      v-model="constraintForm.ageDisable"
                      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="constraintForm.ageDisable"
                  :span="22"
                  style="display: flex; padding-left: 70px"
                >
                  <el-form-item label="最小年龄" prop="ageMin" style="margin-right: 40px">
                    <el-input-number v-model="constraintForm.ageMin" :step="1" :min="0" />
                  </el-form-item>
                  <el-form-item label="最大年龄" prop="ageMax">
                    <el-input-number v-model="constraintForm.ageMax" :step="1" :min="0" />
                  </el-form-item>
                </el-col>
              </el-row>

              <div>
                <el-button
                  type="primary"
                  :loading="saveConstraintLoading"
                  @click="saveConstraint"
                  >{{ saveConstraintLoading ? '' : '保存' }}</el-button
                >
              </div>
            </el-form>
          </el-collapse-item> -->

          <el-collapse-item class="general-settings" :name="ActiveEnum.issue">
            <template #title>
              <div class="settings-header">
                <h4>项目发布</h4>
                <el-button class="collapse-btn">{{ toggleText(ActiveEnum.issue) }}</el-button>
              </div>
            </template>
            <el-form
              ref="issueFormRef"
              size="large"
              :model="issueForm"
              :rules="issueRules"
              :disabled="infoForm.enable === PublishType.running"
              label-position="top"
            >
              <el-row>
                <el-col :span="11">
                  <el-form-item label="受试者代码规则" prop="subIdRule">
                    <select-form
                      v-model="issueForm.subIdRule"
                      :options="dictData[dictIdMaps.subIdRule]"
                      :multiple="false"
                      :default-props="{ label: 'value', value: 'code' }"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="11" class="p-l-2 flex flex-items-center">
                  <span class="mt-[12px]"
                    >科研人员可以选择“手动填写|自动生成”设置受试者代码生成规则</span
                  >
                </el-col>

                <el-col :span="11">
                  <el-form-item label="项目版本号" prop="versionValue">
                    <el-input
                      v-model="issueForm.versionValue"
                      :placeholder="$t('form.placeholder')"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div>
              <el-button
                v-if="
                  infoForm.enable === PublishType.building || infoForm.enable === PublishType.pause
                "
                type="primary"
                :loading="saveIssueLoading"
                @click="publicIssue"
                >{{ saveIssueLoading ? '' : '项目发布' }}</el-button
              >
              <el-button
                v-else-if="infoForm.enable === PublishType.running"
                type="warning"
                :loading="saveIssueLoading"
                @click="unpublishIssue"
                >{{ saveIssueLoading ? '' : '项目暂停' }}</el-button
              >
            </div>
            <div class="issue-history">
              <!-- <h4>现有研究中心</h4> -->
              <div v-loading="projectHistoryState.loading" class="common-card">
                <div class="card-title">
                  <span class="font-bold">发布记录</span>
                  <span class="total-num">{{ projectHistoryState.total }}</span>
                </div>
                <template v-if="projectHistoryState.data.length > 0">
                  <ul class="p-l-16 p-r-16">
                    <li
                      v-for="data in projectHistoryState.data"
                      :key="data.id"
                      class="p-b-10 p-t-10 border-b-1 border-b-[--border-color] border-b-solid flex flex-justify-between"
                    >
                      <div>
                        <div>
                          <span class="m-r-10">{{ data.title }}</span>

                          <span class="font-size-12">{{ data.descr }}</span>
                        </div>
                        <div class="font-size-12">{{ data.createTime }}</div>
                      </div>

                      <!-- <el-button link type="danger" @click="delOrg(data.id)">
                        <el-icon class="font-size-18"><Remove /></el-icon>
                      </el-button> -->
                    </li>
                  </ul>

                  <!-- <pagination
                    v-model:currentPage="pageObj.pageNum"
                    v-model:pageSize="pageObj.pageSize"
                    :total="pageObj.total"
                    @pagination="search"
                  /> -->
                </template>
                <el-empty v-else description="暂无数据" :image-size="200" />
              </div>
            </div>
          </el-collapse-item>

          <el-collapse-item class="general-settings" :name="ActiveEnum.setting">
            <template #title>
              <div class="settings-header">
                <h4>高级设置</h4>
                <el-button class="collapse-btn">{{ toggleText(ActiveEnum.setting) }}</el-button>
              </div>
            </template>

            <div>
              <div class="sub-section">
                <h4 class="c-warning">项目锁库/解锁</h4>
                <p>
                  项目数据收集完成后，你可进行项目锁库操作，锁库后不可进行受试者数据修改与审核，项目锁库后你可通过解锁操作，解除项目锁定。
                </p>
                <el-button type="warning">项目锁库</el-button>
              </div>
              <div class="sub-section">
                <h4 class="c-warning">项目归档</h4>
                <p>
                  在本项目完成数据导出、文档打印等归档事宜后，你可对项目进行归档操作，此研究正式结束。
                </p>
                <el-button type="warning">项目归档</el-button>
              </div>
              <div class="sub-section">
                <h4 class="c-danger">清除数据</h4>
                <p>仅支持测试环境与演示环境下清除数据，清除数据操作不可逆，无法对数据进行恢复。</p>
                <el-button type="danger">清除数据</el-button>
              </div>
              <div class="sub-section">
                <h4 class="c-danger">删除项目</h4>
                <p>
                  仅支持测试环境与演示环境下删除项目，项目删除后将无法访问且录入的数据也会被删除，对于已删除的项目你可以在7天内撤销删除操作。
                </p>
                <el-button type="danger">删除项目</el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </current>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

import { ElMessage } from 'element-plus'

import SelectForm from '@/components/Form/Select.vue'
import HoldUpload from '@/components/Upload/index.vue'
import Current from '../../current/index.vue'

import OrgApi from '@/api/backend/organization'
import ProjectApi from '@/api/project'
import ProjectInfoApi from '@/api/project/info'
import ProjectLogApi from '@/api/project/log'
import { useDict } from '@/api/uses'

import { useUserStore } from '@/store/user'

import { formatUrl } from '@/utils/common/formatUrl'
import { parseTime } from '@/utils/time'

// import { commonHandle, Pagination } from '@/views/mixins/common'
import IBaseObj from '#/index'
import type { FormInstance } from 'element-plus'

const { uid } = useUserStore()

const { pid } = useRoute().query

const { dictIdMaps, getDictData, dictData }: IBaseObj = useDict()

getDictData()

enum ActiveEnum {
  info,
  issue,
  setting,
}
const activeNames = ref([ActiveEnum.info])

const toggleText = (name: ActiveEnum) => {
  return activeNames.value.includes(name) ? '收起' : '展开'
}

const orgList = ref([])

const getOrgData = async () => {
  const ret = await OrgApi.getOrgList()
  orgList.value = ret || []
}
getOrgData()

const infoFormRef = ref<FormInstance>()
const infoRules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  license: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  nameShort: [{ required: true, message: '请输入简要标题', trigger: 'blur' }],
}

const infoForm: IBaseObj = reactive({
  license: '',
  name: '',
  nameShort: '',
  keyValue: '',
  indications: '',
  depict: '',
  phase: '',
  cycle: [],
  expectStartDate: '',
  expectEndDate: '',
  enable: '',
  icon: '',
  sort: '',
})
const constraintForm: IBaseObj = reactive({
  expectNum: 1,
  expectDisable: false,
  restrictSex: '',
  ageDisable: false,
  ageMin: 0,
  ageMax: 0,
})

// const disabledStartDate = (time: Date) => {
//   return infoForm.expectEndDate ? time.getTime() > +new Date(infoForm.expectEndDate) : false
// }

// const disabledEndDate = (time: Date) => {
//   return infoForm.expectStartDate ? time.getTime() < +new Date(infoForm.expectStartDate) : false
// }

const loading = ref(false)
const search = async () => {
  loading.value = true
  try {
    const ret = await ProjectApi.getProjectById(pid as string)
    Object.keys(infoForm).forEach((key) => {
      if (key === 'expectStartDate') {
        // infoForm[key] = parseTime(ret[key], '{y}-{m}-{d}')
        infoForm.cycle = [
          parseTime(ret.expectStartDate, '{y}-{m}-{d}'),
          parseTime(ret.expectEndDate, '{y}-{m}-{d}'),
        ]
      } else {
        infoForm[key] = ret[key]
      }
    })
    Object.keys(constraintForm).forEach((key) => {
      constraintForm[key] = ret[key]
    })
    Object.keys(issueForm).forEach((key) => {
      issueForm[key] = ret[key]
    })
  } finally {
    loading.value = false
  }
}
search()

const uploadSuccess = (file: any) => {
  infoForm.value.logo = file.file.prepareData
}

const saveInfoLoading = ref(false)
const saveInfo = () => {
  infoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      saveInfoLoading.value = true
      try {
        const { cycle, phase, sort } = infoForm
        const [expectStartDate, expectEndDate] = cycle
        const phaseValue = dictData.value[dictIdMaps.projectPhase].find(
          (v: { code: number }) => v.code === phase
        )?.value
        const sortValue = dictData.value[dictIdMaps.projectType].find(
          (v: { code: number }) => v.code === sort
        )?.value

        const ret = await ProjectApi.updateProject({
          pid,
          uid,
          ...infoForm,
          expectStartDate: expectStartDate || '',
          expectEndDate: expectEndDate || '',
          phaseValue,
          sortValue,
        })
        if (ret) {
          ElMessage({
            message: '修改成功！',
            type: 'success',
          })
          search()
        }
      } finally {
        saveInfoLoading.value = false
      }
    }
  })
}

// const constraintFormRef = ref<FormInstance>()
// const constraintRules = {
//   expectNum: [{ required: true, message: '请输入受试者数量', trigger: 'change' }],
// }
// const saveConstraintLoading = ref(false)
// const saveConstraint = () => {
//   constraintFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       saveConstraintLoading.value = true
//       try {
//         const ret = await ProjectApi.updateProject({
//           pid,
//           uid,
//           ...constraintForm,
//         })
//         if (ret) {
//           ElMessage({
//             message: '修改成功！',
//             type: 'success',
//           })
//           search()
//         }
//       } finally {
//         saveConstraintLoading.value = false
//       }
//     }
//   })
// }

/** ********** 项目发布 start ********** */
const issueFormRef = ref<FormInstance>()
const issueForm: IBaseObj = reactive({
  subIdRule: '',
  versionValue: '',
})
const issueRules = {
  // expectNum: [{ required: true, message: '请输入受试者数量', trigger: 'change' }],
}

const enum PublishType {
  building = 100900, // 构建中
  running, // 进行中
  pause, // 暂停
}
const saveIssueLoading = ref(false)
const publicIssue = () => {
  issueFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      saveIssueLoading.value = true
      try {
        const ret = await ProjectInfoApi.publishProject({
          pid,
          ...issueForm,
        })
        if (ret) {
          ElMessage({
            message: '发布成功！',
            type: 'success',
          })
          search()
          getPublishList()
        }
      } finally {
        saveIssueLoading.value = false
      }
    }
  })
}
const unpublishIssue = async () => {
  saveIssueLoading.value = true
  try {
    const ret = await ProjectInfoApi.unpublishProject(pid as string)
    if (ret) {
      ElMessage({
        message: '暂停成功！',
        type: 'success',
      })
      search()
      getPublishList()
    }
  } finally {
    saveIssueLoading.value = false
  }
}

/** ********** 项目发布历史 start ********** */
const projectHistoryState: IBaseObj = reactive({
  loading: false,
  data: [],
  total: 0,
})

const getPublishList = async () => {
  try {
    projectHistoryState.loading = true
    const ret = await ProjectLogApi.getProjectPublishLog(pid as string)
    projectHistoryState.data = ret || []
    projectHistoryState.total = ret.length
  } finally {
    projectHistoryState.loading = false
  }
}
getPublishList()
/** ********** 项目发布历史 end ********** */
/** ********** 项目发布 end ********** */
</script>

<style lang="scss" scoped>
.center-container {
  width: 990px;
  padding: 0 16px 20px;
  margin: 0 auto;
}

.common-header {
  height: 48px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e5e5e5;
}

.general-content {
  padding-top: 10px;

  :deep() {
    .el-collapse {
      border: none;
    }
    .el-collapse-item {
      &__header {
        padding-top: 10px;
        background: transparent;

        h4 {
          color: #2e2e2e;
        }
      }

      &__arrow {
        display: none;
      }

      &__wrap,
      &__content {
        background: transparent;
      }

      &__content {
        padding-top: 10px;
      }

      &:last-child {
        .el-collapse-item__wrap {
          border-bottom: none;
        }
      }
    }

    .el-form-item__label {
      font-weight: bold;
    }
  }
}

.settings-header {
  position: relative;
  width: 100%;

  .collapse-btn {
    position: absolute;
    right: 4px;
    top: 4px;
  }

  h4 {
    font-size: 16px;
  }
}

.sub-section {
  margin-bottom: 32px;
  padding: 16px;
  border: 1px solid #e5e5e5;
  background-color: #fafafa;

  h4 {
    margin: 10px 0;
    font-size: 16px;
    font-weight: 600;
  }

  p {
    margin-bottom: 1rem;
  }
}

.w100 {
  :deep() {
    .el-date-editor,
    .el-input__wrapper {
      width: 100%;
    }
  }
}

.tar {
  text-align: right;
}

.c-warning {
  color: var(--el-color-warning);
}

.c-danger {
  color: var(--el-color-danger);
}

.issue-history {
  padding-top: 22px;

  &__title {
    padding-bottom: 10px;
    font-weight: 700;
    font-size: 15px;
    color: var(--el-text-color-regular);
    border-bottom: 1px solid var(--border-color);
  }
  &__body {
    padding-top: 10px;
  }

  h4 {
    margin: 10px 0;
  }

  .common-card {
    padding: 0 0 16px;
    border: 1px solid #e5e5e5;
    background-color: #fafafa;
  }

  .card-title {
    padding: 6px 16px;
    line-height: 36px;
    background-color: #fafafa;
    border-bottom: 1px solid #e5e5e5;
  }

  .total-num {
    position: relative;
    top: -4px;
    display: inline-block;
    height: 17px;
    margin-top: -5px;
    margin-left: 5px;
    line-height: 16px;
    padding: 1px 5px;
    border-radius: 50%;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.07);
    color: #707070;
    text-align: center;
    vertical-align: baseline;
  }
}

.icon-uploader {
  :deep() {
    .el-upload {
      width: 180px;
      height: 180px;
      line-height: 180px;
    }
  }
}
</style>
